package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    //注入微信开发相关属性,里面封装了appid和secret,以及一些重要属性
    @Autowired
    private WeChatProperties weChatProperties;

    //微信登录
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1.通过HttpClient，构造登录凭证校验请求
        //构造请求参数,这几个属性是微信官方文档中指定的必须要有这四个参数
        Map<String, String> paramMap = new HashMap<>();
        //weChatProperties.getAppid()获取小程序id对应在配置文件application-dev.yml里映射到了appid这个属性
        paramMap.put("appid",weChatProperties.getAppid());
        //weChatProperties.getSecret()获取小程序密钥对应在配置文件application-dev.yml里映射到了secret这个属性
        paramMap.put("secret",weChatProperties.getSecret());
        //前端传来的code
        paramMap.put("js_code",userLoginDTO.getCode());
        //授权类型
        paramMap.put("grant_type","authorization_code");
        //调用Httpclientutil工具类，发送请求,Httpclientutil是一个提前写好的工具类(不是官方的)，可以发送get请求，post请求
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("微信登录返回结果：{}",res);
        //2.解析登录结果获取openid,//openid微信用户唯一标识,在User类中定义了openid属性
        //  JSONObject.parseObject(res)将res转换成JSONObject对象,并转换成字符串
        String openid = (String) JSONObject.parseObject(res).get("openid");
        //3.判断openid是否为空
        if (openid == null){
            //登录失败
           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //4.判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        //5.如果是新用户，自动完成注册
        if (user == null){
            user = User.builder()
                    .openid(openid)//放入用户openid
                    .createTime(LocalDateTime.now())//放入用户创建时间
                    .name(openid.substring(0,6))//截取openid的前6位当默认用户名
                    .build();
            userMapper.insert(user);
            log.info("新用户自动完成注册：{}",user);
        }
        //6.返回登录用户
        log.info("当前用户：{}",user);
        return user;
    }
}
